<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { Api } from '@/api'
import { ElMessage, ElDialog } from 'element-plus'
import base from '@/api/base.js'
import { useUserStore } from '@/stores/user.js'
import { useRouter } from 'vue-router'
import { Document, Packer, Paragraph, TextRun, HeadingLevel, AlignmentType } from 'docx'
import { Plus, ArrowRight } from '@element-plus/icons-vue'

const router = useRouter()
const uploadFileUrl = base.baseUrl + base.uploadFiles

const userStore = useUserStore()
const token = ref(userStore.token)
const user = reactive({ ...userStore.user }) // 获取当前用户信息

// 判断是否为辅导员
const isAssistant = computed(() => {
  const user = userStore.user
  return user?.is_assistantn
})

// 编辑模式
const isEditing = ref(false)

// 更新用户信息
const updateUserInfo = async () => {
  try {
    const payload = {
      id: user.id,
      username: user.username,
      name: user.name,
      phone: user.phone,
      email: user.email,
      avatar: user.avatar,
      introduction: user.introduction,
    }
    const response = await Api.updateUser(payload)
    if (response.data.status === 200) {
      ElMessage.success('个人信息更新成功')
      isEditing.value = false
      userStore.setUser(user)
    } else {
      throw new Error(response.data.message || '更新个人信息失败')
    }
  } catch (error) {
    console.error('更新个人信息失败:', error)
    if (error.response && error.response.status === 403) {
      ElMessage.error('无权限修改其他用户的信息')
    } else {
      ElMessage.error('更新个人信息失败，请稍后再试')
    }
  }
}

// 上传头像
const beforeAvatarUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  if (!isImage) {
    ElMessage.error('只能上传图片文件')
    return false
  }
  return true
}

const handleAvatarSuccess = async (res) => {
  if (res.status === 200) {
    user.avatar = res.data.filePath // 直接使用完整的URL
    await updateUserInfo() // 更新用户信息
    ElMessage.success('头像更新成功')
  } else {
    ElMessage.error('头像上传失败')
  }
}

// 获取测评结果
const evaluationResults = ref([])
const isLoading = ref(false)
const lastFetchedId = ref(null) // 记录最后一次获取的报告 ID

// 获取当前用户的测评结果
const fetchEvaluationResults = async () => {
  if (isLoading.value) return
  isLoading.value = true
  try {
    // 使用当前登录用户的 ID 获取测评结果
    const response = await Api.getUserPsychologyReports({
      user_id: user.id
    })
    evaluationResults.value = response.data.data || []
  } catch (error) {
    console.error('获取测评结果失败:', error)
    ElMessage.error('获取测评结果失败，请稍后再试')
  } finally {
    isLoading.value = false
  }
}

// 修改密码表单
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
})
const isPasswordDialogVisible = ref(false)

// 修改密码
const updatePassword = async () => {
  try {
    if (!passwordForm.oldPassword || !passwordForm.newPassword) {
      ElMessage.error('请输入完整的密码信息')
      return
    }
    const response = await Api.updatePassword({
      oldPassword: passwordForm.oldPassword,
      password: passwordForm.newPassword,
    })
    if (response.data.status === 200) {
      ElMessage.success('密码修改成功')
      isPasswordDialogVisible.value = false
      passwordForm.oldPassword = ''
      passwordForm.newPassword = ''
    } else {
      ElMessage.error(response.data.message || '密码修改失败')
    }
  } catch (error) {
    console.error('修改密码失败:', error)
    ElMessage.error('修改密码失败，请稍后再试')
  }
}

// 退出登录
const logout = () => {
  userStore.clearUser() // 清除用户信息
  ElMessage.success('已退出登录')
  router.push('/login') // 跳转到登录页面
}


onMounted(() => {
  fetchEvaluationResults()
})
</script>

<template>
  <div class="user-profile">
    <!-- 基本信息卡片 -->
    <div class="info-card" @click="router.push('/profile/basic')">
      <div class="avatar-section">
        <el-upload
          class="avatar-uploader"
          :action="uploadFileUrl"
          :headers="{ Authorization: 'Bearer ' + token }"
          :show-file-list="false"
          :before-upload="beforeAvatarUpload"
          :on-success="handleAvatarSuccess"
          @click.stop
        >
          <img v-if="user.avatar" :src="user.avatar.startsWith('http') ? user.avatar : base.baseUrl + user.avatar" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </div>
      <div class="basic-info">
        <div class="info-row">
          <span class="name">{{ user.name || user.username }}</span>
          <span class="account">账号：{{ user.username }}</span>
        </div>
      </div>
      <el-icon class="arrow-icon"><ArrowRight /></el-icon>
    </div>

    <!-- 其他功能卡片 -->
    <div class="function-cards">
      <div class="function-card" @click="router.push('/profile/basic')">
        <span class="label">个人信息</span>
        <el-icon class="arrow-icon"><ArrowRight /></el-icon>
      </div>
      <div class="function-card" @click="router.push('/profile/evaluations')">
        <span class="label">我的测评记录</span>
        <el-icon class="arrow-icon"><ArrowRight /></el-icon>
      </div>
      <div class="function-card" @click="router.push('/profile/appointments')">
        <span class="label">我的预约</span>
        <el-icon class="arrow-icon"><ArrowRight /></el-icon>
      </div>
      <div class="function-card" v-if="user.is_counselor" @click="router.push('/profile/user-all-evaluation-reports')">
        <span class="label">预约用户测评报告</span>
        <el-icon class="arrow-icon"><ArrowRight /></el-icon>
      </div>
      <div class="function-card" v-if="isAssistant" @click="router.push('/profile/book-room')">
        <span class="label">预约教室</span>
        <el-icon class="arrow-icon"><ArrowRight /></el-icon>
      </div>
      <div class="function-card danger" @click="logout">
        <span class="label">退出登录</span>
        <el-icon class="arrow-icon"><ArrowRight /></el-icon>
      </div>
    </div>



    <!-- 修改密码对话框 -->
    <el-dialog v-model="isPasswordDialogVisible" title="修改密码" width="30%" center>
      <el-form :model="passwordForm" label-width="100px">
        <el-form-item label="原密码">
          <el-input v-model="passwordForm.oldPassword" type="password" placeholder="请输入原密码" />
        </el-form-item>
        <el-form-item label="新密码">
          <el-input v-model="passwordForm.newPassword" type="password" placeholder="请输入新密码" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="isPasswordDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="updatePassword">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 心理报告详情弹窗 -->
    <el-dialog v-model="isReportDetailDialogVisible" title="心理报告详情" width="700px">
      <div class="report-detail">
        <h2>{{ reportDetail.questionnaire_title }}</h2>
        <div class="report-summary">
          <p><strong>总分:</strong> {{ reportDetail.total_score }}</p>
        </div>

        <el-divider content-position="center">心理分析详情</el-divider>

        <div v-if="reportDetail.range_results && Object.keys(reportDetail.range_results).length > 0">
          <div v-for="(range, rangeName) in reportDetail.range_results" :key="rangeName" class="range-item">
            <h3>【{{ rangeName }}】(题目{{ range.start_question_id }}-{{ range.end_question_id }})</h3>
            <p><strong>得分:</strong> {{ range.total_score }}</p>
            <p><strong>状态:</strong> {{ range.mental_status }}</p>
            <p><strong>建议:</strong> {{ range.advice }}</p>
          </div>
        </div>

        <el-divider content-position="center">完整报告</el-divider>

        <div class="report-content">
          <pre>{{ reportDetail.content }}</pre>
        </div>
      </div>
      <template #footer>
        <el-button @click="isReportDetailDialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="exportToWord">导出报告</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.user-profile {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
  background-color: #f7f8fa;
  min-height: 100vh;
}

.info-card {
  background-color: white;
  padding: 20px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  cursor: pointer;
  margin-bottom: 15px;
  position: relative;
}

.avatar-section {
  margin-right: 20px;
}

.avatar-uploader :deep(.avatar) {
  width: 60px;
  height: 60px;
  border-radius: 5px;
  object-fit: cover;
}

.basic-info {
  flex: 1;
}

.info-row {
  display: flex;
  flex-direction: column;
}

.name {
  font-size: 18px;
  font-weight: 500;
  color: #333;
  margin-bottom: 5px;
}

.account {
  font-size: 14px;
  color: #999;
}

.arrow-icon {
  color: #999;
  font-size: 16px;
  position: absolute;
  right: 20px;
  top: 50%;
  transform: translateY(-50%);
}

.function-cards {
  background-color: white;
  border-radius: 8px;
  margin-bottom: 15px;
}

.function-card {
  padding: 16px 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  cursor: pointer;
  border-bottom: 1px solid #f0f0f0;
}

.function-card:last-child {
  border-bottom: none;
}

.function-card.danger {
  color: #ff4d4f;
}

.function-card .label {
  font-size: 16px;
}

.evaluation-results {
  background-color: white;
  border-radius: 8px;
  padding: 20px;
}

.evaluation-results h2 {
  margin: 0 0 20px 0;
  font-size: 18px;
  color: #333;
}

.report-box {
  max-height: 400px;
  overflow-y: auto;
}

.report-detail {
  padding: 20px;
}

.report-detail-title {
  font-size: 1.2em;
  font-weight: bold;
  margin-bottom: 15px;
}

.report-detail-content {
  margin-bottom: 20px;
}

.report-detail-section {
  margin-bottom: 15px;
}

.report-detail-section-title {
  font-weight: bold;
  padding: 10px 0;
}

.report-summary {
  background-color: #f8f9fa;
  padding: 15px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.report-content {
  background-color: #fff;
  padding: 15px;
  border: 1px solid #eee;
  border-radius: 8px;
  max-height: 400px;
  overflow-y: auto;
}

.report-content pre {
  white-space: pre-wrap;
  font-family: Arial, sans-serif;
  line-height: 1.6;
}

.range-item {
  background-color: #f8f9fa;
  padding: 15px;
  border-radius: 8px;
  margin-bottom: 15px;
  border-left: 4px solid #409eff;
}

.range-item h3 {
  margin-top: 0;
  color: #409eff;
  font-size: 16px;
}
</style>
